<?php

class Html_Render_Group_Div3
{
    public function render($group)
    {
        $trans = Nuo::get('Translate');
        $tag = $group -> getMeta('tag', 'div');
        $xhtml = array();

        $groupTitle = $group -> getTitle();
        $groupDesc = $group -> getDesc();

        if ($groupTitle && !$group -> getNoTitle())
        {
            if ($groupTitle == '@self')
            {
                $groupTitle = 'title@' . $group -> getName();
            }
            $groupTitle = '<div class="form-group-title">' . $trans -> translate($groupTitle) . '</div>';
        }
        else
        {
            $groupTitle = '';
        }

        $groupDesc = $group -> getTitle();

        if ($groupDesc && !$group -> getNoDesc())
        {
            if ($groupDesc == '@self')
            {
                $groupDesc = 'desc@' . $group -> getName();
            }
            $groupDesc = '<div class="form-group-desc">' . $trans -> translate($groupDesc) . '</div>';
        }
        else
        {
            $groupDesc = '';
        }

        foreach ($group->getElements() as $element)
        {
            $label = $element -> getMeta('label');
            $desc = $element -> getDesc();
            $errors = $element -> getErrors();
            $name = $element->getName();

            $html = $element -> render();

            if ($label && !$element -> getNoLabel())
            {
                if($label == '@self'){
                    $label = 'label@'. $name;
                }
                $label = '<div class="form-element-label"><label>' . $trans -> translate($label) . '</label></div>';
            }
            else
            {
                $label = '';
            }

            if ($desc && !$element -> getNoDesc())
            {
                 if($desc == '@self'){
                    $desc = 'desc@'. $name;
                }
                $desc = '<div class="form-element-desc">' . $trans -> translate($desc) . '</div>';
            }
            $error = '';

            if ($errors)
            {
                $error = '<ul class="form-element-errors"><li>' . implode('</li><li>', $element -> getErrors()) . '</li></ul>';
            }
            $xhtml[] = '<div class="form-element-wrapper">' . $label . '<div class="form-element-card-outer">'. $desc . $error.  $html .'</div>' . '</div>';
        }
        return sprintf('<%s %s>%s %s %s</div></%s>', $tag, $group -> flatAttrib(), $groupTitle, $groupDesc, implode(PHP_EOL, $xhtml), $tag);
    }

}
